JQUERY HTML ()

Vignesh S



jQuery html ()

The html() method in jQuery is used to get or set the HTML content of selected elements.

Syntax 

  • To get HTML content: $(selector).html();
    This returns the HTML content of the first matched element.
  • To set HTML content: $(selector).html(content);
    This sets the HTML content for all matched elements.
  • To set content by calling function: $(selector).html(function (index, currentcontent)) ;
Parameter Details:
1. Content
 - Purpose: This crucial parameter is used to define the new content for the chosen elements. 
- Capability: It supports inclusion of HTML tags within the content.
2. Function (index, currentContent) 
 - Purpose: This optional parameter allows the use of a function to generate new content for the selected elements. 
 - Components: 
Index: Indicates the position of the element within the set.
currentContent: Reflects the existing HTML content of the selected element.
Example 
To get HTML content:
<!DOCTYPE html>
<html>
<head>
  <title>jQuery html() Example</title>
  </head>
<body>
  <div id="myDiv">Hello <strong>World</strong>!</div>
  <script>
$(document).ready(function() {
      var content = $('#myDiv').html(); // Get the HTML content of the div
   console.log(content); // Outputs: Hello <strong>World</strong>!
    });
  </script>
</body>
</html>
To set HTML Content:
<!DOCTYPE html>
<html>
<head>
  <title>jQuery html() Example</title>
</head>
<body>
  <div id="myDiv">Hello <strong>World</strong>!</div>
  <button id="changeContent">Change Content</button>
  <script>
    $(document).ready(function() {
     $('#changeContent').click(function() {  $('#myDiv').html('<em>New Content</em> with HTML tags!'); // Set new HTML content
      });
    });
  </script>
</body>
</html>
To set content by using function:
<!DOCTYPE html>
<html>
<head>
  <title>jQuery html() Example</title>
</head>
<body>
 <div id="myDiv">Hello         <strong>World</strong>!</div>
<button id="changeContent">Update Content</button>
<script>
    $(document).ready(function() {
     $('#changeContent').click(function() { $('#myDiv').html(function(index, currentContent) {
          return currentContent + " Updated content at index " + index;
        });
      });
    });
  </script>
</body>
</html>



Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send